<template>
  <div class="main">
    <div class="part">
      <div class="p-title">
        <div class="title">药品目录</div>
        <div class="catalog">
          <el-select
            v-model="selectedWarehouseId"
            class="m-2"
            placeholder="请选择"
            @change="catalogChange"
          >
            <el-option
              v-for="item in catalogList"
              :key="item.warehouseId"
              :label="item.name"
              :value="item.warehouseId"
            />
          </el-select>
          <MyToolTip
            content="药品目录用于管理居民用户可在万户医学院App内购买的药品明细及药品对应销售价。\n每个中心药房都拥有一个独立的药品目录，当您拥有多个中心药房时，可通过切换目录来编辑不同的中心药房目录。"
          />
        </div>
      </div>
      <div class="p-cont">
        <div class="opr">
          <div class="opr-left">
            <el-button type="primary" @click="showAddDrugPanel"
              >添加药品</el-button
            >
            <el-button plain>批量导入</el-button>
            <el-button link>
              <IconifyIconOnline
                icon="material-symbols:download"
                width="24px"
                height="24px"
              />下载导入模板</el-button
            >
          </div>
          <div class="opr-right">
            <el-input
              v-model="searchContent"
              placeholder="请输入关键词进行搜索"
              @change="searchDrugs"
            >
              <template #append>
                <el-button :icon="Search" />
              </template>
            </el-input>
          </div>
        </div>
        <div class="table-wrap">
          <el-table
            :data="drugList"
            style="width: 100%"
            stripe
            @selection-change="tableSelectionChange"
          >
            <el-table-column type="selection" />
            <el-table-column prop="drugCode" label="药品编码" width="180" />
            <el-table-column prop="commonName" label="通用名" width="180" />
            <el-table-column prop="productName" label="商品名" />
            <el-table-column prop="productName" label="类型">
              <template #default="scope">
                {{ String(scope.row.sortType) === "0" ? "环保药" : "普通药" }}
              </template>
            </el-table-column>

            <el-table-column prop="specification" label="规格" />
            <el-table-column prop="producerName" label="生产企业" />
            <el-table-column prop="approvalNumber" label="批准文号" />
            <el-table-column prop="priceCent" label="零售价" />
            <el-table-column fixed="right" label="操作" width="200">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="showProPic(scope.row)"
                  :disabled="!scope.row.outerPackagePicUrl"
                  style="width: 80px; text-align: left"
                  >{{
                    scope.row.outerPackagePicUrl
                      ? "商品图&nbsp;&nbsp;"
                      : "暂无图片"
                  }}</el-button
                >
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="changPrice(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="deleteDrug(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="del-btn">
          <div class="del-left">
            <el-button type="primary" @click="plDeleteDrugs"
              >批量删除</el-button
            >
          </div>
          <div class="del-right">
            <myPagination
              :total="listNum || 0"
              @currentChange="currentChange"
              ref="myPaginationRef"
            />
          </div>
        </div>
        <div class="page">
          <!-- <div class="page-left">共{{ listNum }}条数据</div> -->
        </div>
      </div>
      <el-dialog
        v-model="picDialogVisible"
        :title="curDrug && curDrug.commonName"
        width="600"
      >
        <img :src="curDrug && curDrug.outerPackagePicUrl" />
      </el-dialog>
      <el-dialog
        v-model="priceDialogVisible"
        :title="curDrug && curDrug.commonName"
        width="800"
      >
        <el-row :gutter="20">
          <el-col :span="4">原价格：</el-col>
          <el-col :span="10">{{ curDrug.priceCent }}</el-col>
        </el-row>
        <div style="margin-top: 20px" />
        <el-row :gutter="20">
          <el-col :span="4">新价格：</el-col>
          <el-col :span="10"
            ><el-input v-model="drugNPrice" placeholder="新价格"
          /></el-col>
        </el-row>
        <el-row :gutter="20" class="mt20">
          <el-col :span="4">类型：</el-col>
          <el-col :span="10">
            <el-radio-group v-model="drugSortType">
              <el-radio label="1">普通药</el-radio>
              <el-radio label="0">环保药</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
        <div style="margin-top: 20px" />

        <el-row>
          <el-col :span="24">
            <el-button type="primary" @click="sumitNewPrice">提交</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog
        v-model="prePriceDialogVisible"
        :title="curDrug && curDrug.commonName"
        width="800"
      >
        <div style="margin-top: 20px" />
        <el-row :gutter="20" style="align-items: center">
          <el-col :span="2">价格：</el-col>
          <el-col :span="10"
            ><el-input v-model="preDrugNPrice" placeholder="请输入价格"
          /></el-col>
        </el-row>
        <div style="margin-top: 20px" />
        <el-row :gutter="20" class="mt20">
          <el-col :span="2">类型：</el-col>
          <el-col :span="10">
            <el-radio-group v-model="drugSortType">
              <el-radio label="1">普通药</el-radio>
              <el-radio label="0">环保药</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" style="text-align: center">
            <el-button type="primary" @click="preNewPrice">提交</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog v-model="addDrugDialogVisible" title="添加药品" width="800">
        <div class="dialog-adddrug">
          <div class="search">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input
                  v-model="searchCommonName"
                  placeholder="请输入药品的通用名"
                  @change="addSearchDrugs"
                />
              </el-col>
              <el-col :span="8">
                <el-input
                  v-model="searchProductName"
                  placeholder="请输入药品的商品名"
                  @change="addSearchDrugs"
                />
              </el-col>
              <el-col :span="2">
                <el-checkbox
                  v-model="includePic"
                  label="有图片"
                  true-label="1"
                  false-label="0"
                  size="large"
                />
              </el-col>
              <el-col :span="4" style="text-align: right">
                <el-button type="primary" @click="addSearchDrugs"
                  >搜索</el-button
                >
              </el-col>
            </el-row>
          </div>
          <el-table
            :data="addSearchDrugsList"
            style="width: 100%; margin-bottom: 10px"
          >
            <el-table-column prop="drugCode" label="药品编码" width="120" />
            <el-table-column prop="commonName" label="通用名" width="120" />
            <el-table-column prop="productName" label="商品名" />
            <el-table-column prop="productName" label="图片">
              <template #default="scope">
                <el-image :src="scope.row.outerPackagePicUrl">
                  <template #placeholder>
                    <div style="color: gray">无</div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="specification" label="规格" />
            <el-table-column prop="producerName" label="生产企业" />
            <el-table-column prop="approvalNumber" label="批准文号" />
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="addDurgToHouse(scope.row)"
                  :disabled="scope.row.disabled ? true : false"
                  >添加</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <myPagination
            :total="addSearchTotalNum || 0"
            @currentChange="addSearchCurrentChange"
            ref="addDurgPaginationRef"
          />
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { Search } from "@element-plus/icons-vue";
import {
  getSalesCatalog,
  getSalesDrugs,
  changeDrugPrice,
  deleteDrugApi,
  addDrugApi,
  searchCommonDrugsApi
} from "@/api/supply";
import myPagination from "@/components/myPagination.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";
import MyToolTip from "@/components/myToolTip.vue";

const searchContent = ref<string>("");
const catalogList = ref([]);
const selectedWarehouseId = ref("");
const selectedCatalogId = ref("");
const listNum = ref(0);
const myPaginationRef = ref();
const drugList = ref([]);
const picDialogVisible = ref(false);
const curDrug = ref(null);
const priceDialogVisible = ref(false);
const drugNPrice = ref("");
const drugSortType = ref("0");
const userId = useUserStoreHook().userInfo.user;
const plSelectedDrugs = ref(null);
const addDrugDialogVisible = ref(false);
const searchCommonName = ref("");
const searchProductName = ref("");
const includePic = ref(0);
const searchResult = ref([]);
const addDurgPaginationRef = ref(null);
const addSearchDrugsList = ref(null);
const addSearchTotalNum = ref(0);
const preDrugNPrice = ref("");

const localSelectedWarehouseIdKey = userId + selectedWarehouseId.value;

const prePriceDialogVisible = ref(false);

function currentChange() {
  getDrugs();
}
async function getDrugs() {
  if (selectedWarehouseId.value) {
    const listRes = await getSalesDrugs(selectedWarehouseId.value, {
      skip:
        (myPaginationRef.value.currentPage - 1) *
        myPaginationRef.value.curPageSize,
      limit: myPaginationRef.value.curPageSize,
      search: searchContent.value
    });
    selectedCatalogId.value = listRes.catalogId;
    drugList.value = listRes.list;
    if (myPaginationRef.value.currentPage === 1) {
      listNum.value = listRes.total;
    }
  }
}
function catalogChange() {
  // 对用户进行隔离
  localStorage.setItem(localSelectedWarehouseIdKey, selectedWarehouseId.value);
  getDrugs();
}
function searchDrugs() {
  myPaginationRef.value.currentPage = 1;
  getDrugs();
}

function showAddDrugPanel() {
  addDrugDialogVisible.value = true;
}

function showProPic(drug) {
  console.log("drug:", drug);
  curDrug.value = drug;
  picDialogVisible.value = true;
}

function changPrice(drug) {
  priceDialogVisible.value = true;
  curDrug.value = drug;
  drugSortType.value = drug.sortType;
}
function deleteDrug(drug) {
  ElMessageBox.alert(`确定要删除"${drug.commonName}"吗`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(async () => {
    await deleteDrugApi(selectedCatalogId.value, {
      userId,
      drugIds: drug.drugId
    });
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    await getDrugs();
  });
  return;
}
async function sumitNewPrice() {
  // 获取被选中目录的目录id
  const newPrice = drugNPrice.value;
  if (!/\d+(\.\d{1,2})?/.test(newPrice)) {
    ElMessageBox.alert("价格必须是数字，且最多保留小数点后2位", "提示", {
      confirmButtonText: "确定"
    });
    return;
  }

  if (Number(newPrice) <= 0) {
    ElMessageBox.alert("价格不能为0或者负数", "提示", {
      confirmButtonText: "确定"
    });
    return;
  }

  if (drugSortType.value === "") {
    ElMessageBox.alert("类型不能为空", "提示", {
      confirmButtonText: "确定"
    });
    return;
  }
  try {
    await changeDrugPrice(selectedCatalogId.value, {
      userId,
      drugId: curDrug.value.drugId,
      price: newPrice,
      sortType: drugSortType.value
    });
    drugNPrice.value = "";
    ElMessage({
      message: "调价成功",
      type: "success"
    });
    await getDrugs();
    priceDialogVisible.value = false;
  } catch (e) {
    ElMessage({
      message: "请求服务器失败，请稍后重试",
      type: "error"
    });
  }
}

function tableSelectionChange(selection) {
  plSelectedDrugs.value = selection;
  // console.log("selection:", selection);
}

async function plDeleteDrugs() {
  ElMessageBox.alert(`确定要删除这些被选中的药品吗`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(async () => {
    const deleteDrugsIdList = plSelectedDrugs.value.map(item => {
      return item.drugId;
    });

    await deleteDrugApi(selectedCatalogId.value, {
      userId,
      drugIds: deleteDrugsIdList.join(",")
    });
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    await getDrugs();
  });
}

function addSearchCurrentChange() {
  addSearchDrugs();
}
// 新增药品时，搜索药品
async function addSearchDrugs() {
  const addSRes = await searchCommonDrugsApi({
    commonName: searchCommonName.value,
    productName: searchProductName.value,
    includePic: includePic.value,
    skip:
      (addDurgPaginationRef.value.currentPage - 1) *
      addDurgPaginationRef.value.curPageSize,
    limit: addDurgPaginationRef.value.curPageSize
  });

  addSearchDrugsList.value = addSRes.list;
  if (addDurgPaginationRef.value.currentPage === 1) {
    addSearchTotalNum.value = addSRes.total;
  }
}

async function preNewPrice() {
  const newPrice = preDrugNPrice.value;
  if (!/\d+(\.\d{1,2})?/.test(newPrice)) {
    ElMessageBox.alert("价格必须是数字，且最多保留小数点后2位", "提示", {
      confirmButtonText: "确定"
    });
    return;
  }
  if (Number(newPrice) <= 0) {
    ElMessageBox.alert("价格不能为0或者负数", "提示", {
      confirmButtonText: "确定"
    });
    return;
  }
  if (drugSortType.value === "") {
    ElMessageBox.alert("类型不能为空", "提示", {
      confirmButtonText: "确定"
    });
    return;
  }
  prePriceDialogVisible.value = false;
  const res = await addDrugApi(selectedCatalogId.value, {
    baseDrugId: curDrug.value.baseDrugId,
    userId,
    price: preDrugNPrice.value,
    sortType: drugSortType.value
  });
  // console.log("res:", res);
  if (res.drugId) {
    ElMessage({
      message: "添加药品成功",
      type: "success"
    });
    curDrug.value.disabled = true;
  }
  // addSearchDrugs();
  getDrugs();
}

async function addDurgToHouse(drug) {
  if (!selectedCatalogId.value) {
    ElMessage({
      message: "请先选择药品目录",
      type: "error"
    });
    return;
  }
  // 显示调价窗口
  prePriceDialogVisible.value = true;
  curDrug.value = drug;
}
onMounted(async () => {
  catalogList.value = await getSalesCatalog();
  // console.log(
  //   'localStorage.getItem("selectedWarehouseId"):',
  //   localStorage.getItem("selectedWarehouseId")
  // );
  selectedWarehouseId.value =
    Number(localStorage.getItem(localSelectedWarehouseIdKey)) ||
    catalogList.value[0]?.warehouseId;
  await getDrugs();
});
</script>
<style scoped lang="scss">
::v-deep(.el-backtop) {
  display: none !important;
}

.main {
  .part {
    .p-title {
      justify-content: flex-start;

      .catalog {
        display: flex;
        align-items: center;
        margin-right: 0;
        .m-2 {
          width: 280px;
        }
      }
    }
  }
}

.opr {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .opr-right {
    width: 300px;
  }
}

.table-wrap {
  margin-top: 20px;
}

.del-btn {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .page-left {
    color: #bbb;
  }
}
</style>
